package hu.mapro.gwtui.server;

import java.util.Collection;

import com.google.web.bindery.requestfactory.server.ServiceLayerDecorator;
import com.google.web.bindery.requestfactory.shared.Locator;
import com.google.web.bindery.requestfactory.shared.ServiceLocator;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class GwtUiServiceLayerDecorator extends ServiceLayerDecorator {

	@Override
	public <T extends Locator<?, ?>> T createLocator(Class<T> clazz) {
		return lookup(clazz);
	}

	protected <T> T lookup(Class<T> clazz) {
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(GwtUiRequestFactoryServlet.getThreadLocalServletContext());
		return context.getBean(clazz);
	}
	
	@Override
	public <T extends ServiceLocator> T createServiceLocator(Class<T> clazz) {
		return lookup(clazz);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void setProperty(Object domainObject, String property,
			Class<?> expectedType, Object value) {
		if (Collection.class.isAssignableFrom(expectedType)) {
			
			Collection newValue = (Collection) value;
			Collection currentValue = (Collection) getTop().getProperty(domainObject, property);
			
			if (currentValue!=null) {
				currentValue.clear();
				
				if (newValue!=null) {
					currentValue.addAll(newValue);
				}
				
				return;
			} 
			
		}
		
		super.setProperty(domainObject, property, expectedType, value);
	}
}
